package org.dromara.system.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.system.domain.SkyHumanDishonest;
import org.dromara.system.domain.bo.ArchivesBo;
import org.dromara.system.utils.SkyEyeClientUtil;
import org.dromara.system.utils.SkyEyeProperties;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.SkyPunishmentBo;
import org.dromara.system.domain.vo.SkyPunishmentVo;
import org.dromara.system.domain.SkyPunishment;
import org.dromara.system.mapper.SkyPunishmentMapper;
import org.dromara.system.service.ISkyPunishmentService;

import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 行政处罚Service业务层处理
 *
 * @author Lion Li
 * @date 2024-09-20
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class SkyPunishmentServiceImpl implements ISkyPunishmentService {

    private final SkyPunishmentMapper baseMapper;

    /**
     * 查询行政处罚
     */
    @Override
    public SkyPunishmentVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询行政处罚列表
     */
    @Override
    public TableDataInfo<SkyPunishmentVo> queryPageList(SkyPunishmentBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SkyPunishment> lqw = buildQueryWrapper(bo);
        Page<SkyPunishmentVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询行政处罚列表
     */
    @Override
    public List<SkyPunishmentVo> queryList(SkyPunishmentBo bo) {
        LambdaQueryWrapper<SkyPunishment> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<SkyPunishment> buildQueryWrapper(SkyPunishmentBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SkyPunishment> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getDepartmentName()), SkyPunishment::getDepartmentName, bo.getDepartmentName());
        return lqw;
    }

    /**
     * 新增行政处罚
     */
    @Override
    public Boolean insertByBo(SkyPunishmentBo bo) {
        SkyPunishment add = MapstructUtils.convert(bo, SkyPunishment.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改行政处罚
     */
    @Override
    public Boolean updateByBo(SkyPunishmentBo bo) {
        SkyPunishment update = MapstructUtils.convert(bo, SkyPunishment.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SkyPunishment entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除行政处罚
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public void mergeDataByCandidate(String candidate) {
        ArchivesBo bo = new ArchivesBo();
            bo.setKeyword(candidate);

        JSONObject jo = SkyEyeClientUtil.query(bo, SkyEyeProperties.PUNISHMENT_INFO);

        if(!jo.isEmpty() && jo.getInt("total") != 0) {
            JSONArray array = jo.getJSONArray("items");
            ObjectMapper mapper = new ObjectMapper();

            try {
                List<SkyPunishment> list = mapper.readValue(array.toString(), new TypeReference<>() {});
                //把以前的数据删除
                baseMapper.deleteByCompanies(candidate);
                //重新插入新数据
                list = list.stream().peek(data -> data.setCompanyName(candidate)).toList();
                baseMapper.insertBatch(list);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("获取行政处罚数据失败", e);
            }
        }
    }
}
